<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" icon="el-icon-plus" style="margin:10px 0;" @click="addTrademark">添加</el-button>
      <el-table v-loading="loading" :data="trademarkList" border style="width: 100%">
        <el-table-column type="index" label="序号" align="center" width="80" />
        <el-table-column prop="tmName" label="品牌名称" width="150" align="center" />
        <el-table-column label="品牌LOGO">
          <template v-slot="{row}">
            <img :src="row.logoUrl" alt="" style="width:100px">
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="{row}">
            <el-button type="warning" icon="el-icon-edit" size="mini" @click="editOneTrademark(row.id)">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteOneTrademarkData(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination style="text-align:center" :current-page="currentPage" :page-sizes="[3,5,10]" :page-size="limit" layout="prev, pager, next, jumper,->,total, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

      <el-dialog :title="tmForm.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
        <el-form ref="tmForm" :model="tmForm" :rules="rules">
          <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
            <el-input v-model="tmForm.tmName" autocomplete="off" style="width:400px" />
          </el-form-item>
          <el-form-item label="品牌logo" :label-width="formLabelWidth" prop="logoUrl">
            <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept=".jpg,.png,.jpeg">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrUpdateOneTrademark">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { reqGetTrademarkList, reqAddOneTrademark, reqDeleteTrademarkData, reqGetOneTrademark, reqUpdateOneTrademark } from '@/api/product/trademark'

export default {
  name: 'Trademark',
  data() {
    return {
      currentPage: 1,
      trademarkList: [],
      limit: 5,
      total: 0,
      dialogFormVisible: false,
      formLabelWidth: '80px',
      form: {},
      imageUrl: '',
      tmForm: {
        // 品牌名字
        tmName: '',
        // 图片链接
        logoUrl: ''
      },
      loading: false,
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        logoUrl: [{ required: true, message: '请选择一张品牌图片', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getTrademarkListData()
  },

  methods: {
    // 获商品列表
    async getTrademarkListData(page = 1) {
      const { limit } = this
      const result = await reqGetTrademarkList(page, limit)
      this.loading = true
      if (result.code === 200) {
        this.trademarkList = result.data.records
        this.total = result.data.total
        this.loading = false
      } else {
        this.$message('获取数据列表失败...')
      }
    },
    handleSizeChange(val) {
      this.limit = val
      this.currentPage = 1
      this.getTrademarkListData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTrademarkListData(val)
    },

    // 上传图片成功后调用此方法
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.tmForm.logoUrl = res.data
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const imgArr = ['image/jpeg', 'image/jpg', 'image/png']
      const isImg = imgArr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImg && isLt2M
    },

    // 添加新的trademark
    async addOrUpdateOneTrademark() {
      this.$refs.tmForm.validate(async valid => {
        if (valid) {
          let result
          if (this.tmForm.id) {
            result = reqUpdateOneTrademark(this.tmForm)
          } else {
            result = await reqAddOneTrademark(this.tmForm)
          }

          if (result.code === 200) {
            this.dialogFormVisible = false
            this.$message.success('添加品牌成功')
            this.currentPage = 1
            this.getTrademarkListData()
          } else {
            this.$message.error({
              type: 'error',
              message: '添加品牌失败'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 删除一个trademark
    deleteOneTrademarkData(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const result = await reqDeleteTrademarkData(id)
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.currentPage = this.trademarkList.length === 1 ? this.currentPage - 1 : this.currentPage
            this.getTrademarkListData()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 获取待更新商品数据
    async editOneTrademark(id) {
      const result = await reqGetOneTrademark(id)
      if (result.code === 200) {
        this.dialogFormVisible = true
        this.tmForm = result.data
        this.imageUrl = result.data.logoUrl
      }
    },

    // 添加商品
    addTrademark() {
      this.tmForm.tmName = ''
      this.imageUrl = ''
      this.dialogFormVisible = true
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
